package com.hl.framework.core.banner;

import cn.hutool.core.thread.ThreadUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.MessageFormat;
import java.util.concurrent.TimeUnit;

/**
 * 项目启动成功后，提供文档相关的地址
 *
 * @author 芋道源码
 */
@Slf4j
public class BannerApplicationRunner implements ApplicationRunner {

    @Value("${server.port}")
    private String port;

    @Override
    public void run(ApplicationArguments args) {

        InetAddress localHost = null;
        try {
            localHost = InetAddress.getLocalHost();
            String ipAddress = localHost.getHostAddress();
            System.out.println("本机IP地址：" + ipAddress);
            printSwaggerUrl(ipAddress);
        } catch (UnknownHostException e) {
            printSwaggerUrl("localhost");
        }

    }

    private void printSwaggerUrl(String ipAddress) {

        String template = "http://"+ipAddress+":{0}/swagger-ui/index.html";
        String result = MessageFormat.format(template, port);

        ThreadUtil.execute(() -> {
            ThreadUtil.sleep(1, TimeUnit.SECONDS); // 延迟 1 秒，保证输出到结尾
            log.info("""
                            
                            ----------------------------------------------------------
                            \t\
                            项目启动成功！
                            \t\
                            swagger文档: \t{}\s
                            ----------------------------------------------------------""",
                    result);
        });
    }

}
